from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from . import constants_oauth
from itsdangerous import BadData


def generate_access_token(openid):
    """
    签名openid
    :param openid: 用户的openid
    :return: access_token
    """
    #  创建序列化器对象
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants_oauth.ACCESS_TOKEN_EXPIRES)
    #  准备待序列化的字典
    data = {'openid': openid}
    #  调用dumps方法进行序列化
    token = serializer.dumps(data)

    return token.decode()


def check_access_token(access_token_openid):
    """反解、反序列化access_token_openid"""
    #  创建序列化对象
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants_oauth.ACCESS_TOKEN_EXPIRES)
    #  反序列化openid密文
    try:
        data = serializer.loads(access_token_openid)
    except BadData:  # openid过期
        return None
    else:
        #  返回openid明文
        return data.get('openid')
